package com.easonji.admin.manager.impl;

import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.dao.AppDAO;
import com.easonji.admin.manager.AppManager;
import com.easonji.admin.mapper.AppMapper;
import com.easonji.admin.model.App;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.easonji.common.constant.Consts;
import com.easonji.common.constant.cache.CacheConsts;
import com.easonji.common.constant.cache.CacheKeyConsts;
import com.easonji.common.node.TreeNode;
import com.easonji.common.util.StringUtils;

/**
 * @ClassName: AppManagerImpl
 * @Description: 应用通用类实现
 * @Author: LiuJun
 * @date: 2018/07/30 18:23
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
public class AppManagerImpl implements AppManager {

    @Resource
    private AppMapper appMapper;

    @Resource
    private AppDAO appDAO;

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.APP_NAME + "'+#appId")
    public String getAppNameById(Integer appId) {
        String result = "";
        Wrapper<App> wrapper = new EntityWrapper<>();
        wrapper.eq("id", appId);
        List<App> apps = appMapper.selectList(wrapper);
        if (StringUtils.isNotEmpty(apps)) {
            result = apps.get(0).getName();
        }
        return result;
    }

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.APP_NAMES + "'+#appIds")
    public String getAppNamesByIds(String appIds) {
        StringBuilder result = new StringBuilder();
        Wrapper<App> wrapper = new EntityWrapper<>();
        String[] ids = StringUtils.split(appIds, Consts.COMMA);
        wrapper.in("id", ids);
        List<App> apps = appMapper.selectList(wrapper);
        if (StringUtils.isEmpty(apps)) {
            return "";
        } else {
            apps.forEach(app -> {
                result.append(",");
                result.append(app.getName());
            });
            return result.substring(1);
        }
    }

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.APP_NAME_ALL + "'")
    public List<TreeNode> queryAppTreeNodes() {
        List<TreeNode> result = appDAO.selectAppTreeNodes();
        return result;
    }

    @Override
    public List<TreeNode> queryAppTreeNodesByUserId(Integer userId) {
        return appDAO.selectAppTreeNodesByUserId(userId);
    }
}
